import React from 'react';
import './index.scss';

export default class Tab extends React.Component {
  constructor(props) {
    super(props);
    const { key , data, } = this.props;
    this.state = {
      selectedKey: key !== undefined ? `${key}` : data[0] !== undefined ? `${data[0].key}` : '',
      selectIndex: 0
    }
    this.myRef = React.createRef();
    this.containerRef = React.createRef();
  }

  componentWillReceiveProps(nextProps) {
    const { key } = nextProps;
    if (key !== this.props.key && key !== this.state.selectedKey) {
      this.setState({
        selectedKey: key
      });
    }
  }

  onTabClick = (e) => {
    const { tabKey } = e.currentTarget.dataset;
    const { onTabSwitch, scroll = false } = this.props;
    const currentTargetStyle = e.currentTarget.getBoundingClientRect();
    const indicatorStyle = this.myRef.current.getBoundingClientRect();
    const containerStyle = this.containerRef.current.getBoundingClientRect();
    let targetLeft = currentTargetStyle.left;
    if (scroll) {
      targetLeft += this.containerRef.current.scrollLeft;
    }
    this.myRef.current.style.left = (targetLeft + currentTargetStyle.width / 2 - indicatorStyle.width / 2 - containerStyle.x) + 'px';
    this.setState({
      selectedKey: tabKey
    }, () => {
      onTabSwitch && onTabSwitch(tabKey);
    });
  }

  componentDidMount() {
    const indicatorStyle = this.myRef.current.getBoundingClientRect();
    const containerStyle = this.containerRef.current.getBoundingClientRect();
    const targetDiv = document.getElementsByClassName('okay-tab-item active');
    if (targetDiv.length === 0) {
      return;
    }
    const targetStyle = targetDiv[0].getBoundingClientRect();
    this.myRef.current.style.left = (targetStyle.left + targetStyle.width / 2 - indicatorStyle.width / 2 - containerStyle.x) + 'px';
  }


  render() {
    const { data = [], type = 'success', scroll = false, className = '' } = this.props;
    const { selectedKey } = this.state;
    return (
      <div className={className !== '' ? className : 'bottom-line top-line'}>
        <div className={`okay-tab ${scroll ? 'scroll' : ''}`} ref={this.containerRef}>
          {
            data.map((item, index) => {
              return (
                <div
                  className={`okay-tab-item ${selectedKey === `${item.key}` ? `active ${type}` : ''}`}
                  onClick={this.onTabClick}
                  data-tab-key={item.key}
                  key={item.key}
                  data-tab-index={index}
                >
                  {item.label}
                </div>
              );
            })
          }
          <div className="indicator" ref={this.myRef} />
        </div>
      </div>
    );
  }
}
